package br.com.main.client.system.morador;

import java.util.Date;
import java.util.List;

import br.com.main.client.ComunServico;
import br.com.main.client.ComunServicoAsync;
import br.com.main.client.system.morador.FinanceiroViewM.Financas;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.TextBox;

public class FinanceiroPresenterM {

	Display display;

	interface Display {

		List<Financas> getList();

		void atualizaTabela();

		TextBox getTbValorTotal();

		HTML getBotaoPagSeguro();

		TextBox getTbPesquisar();

	}

	public FinanceiroPresenterM(Display display) {
		this.display = display;
		bind();
		carregarTabela();
		
	}


	private void CarregaHTML() {
		getServico().pegarFormulario(new AsyncCallback<String>() {
			
			@Override
			public void onSuccess(String arg0) {
				
				display.getTbValorTotal().setEnabled(true);
				String valor = arg0.replace("{$Valor}", display.getTbValorTotal().getValue());
				display.getBotaoPagSeguro().setHTML(valor);
				display.getTbValorTotal().setEnabled(false);
			}
			
			@Override
			public void onFailure(Throwable arg0) {
				display.getTbPesquisar().setValue(arg0.getMessage());
				
			}
		});
		
	}


	private void carregarTabela() {
		getServico().carregarDespesas(new AsyncCallback<List<String[]>>() {

			@SuppressWarnings("deprecation")
			@Override
			public void onSuccess(List<String[]> arg0) {
				DateTimeFormat format = DateTimeFormat.getFormat("d/MM/y");
				Double valor = new Double(0);

				display.getList().clear();

				for (String[] strings : arg0) {

					if("Não".equalsIgnoreCase(strings[3])){
						
						String data = format.format(new Date(strings[2]));

						display.getList().add(new Financas(strings[0], strings[1], data));


						valor = valor + Double.parseDouble(strings[0]);
					}
				}

				getServico().customFormat(valor+"", new AsyncCallback<String>() {
					
					@Override
					public void onSuccess(String arg0) {
						display.getTbValorTotal().setValue(arg0);
						CarregaHTML();
						
					}
					
					@Override
					public void onFailure(Throwable arg0) {
						display.getTbPesquisar().setValue(arg0.getMessage());
						
					}
				});
			
				display.atualizaTabela();

			}

			@Override
			public void onFailure(Throwable arg0) {
				display.getTbPesquisar().setValue(arg0.getMessage());

			}
		});
	}

	private void bind() {


	}
	private ComunServicoAsync getServico() {
		return GWT.create(ComunServico.class);
	}
	
}
